package webapp.filter;

import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.log4j.Logger;

/**
 * @author Neev Information Technologies Pvt. Ltd.
 * 
 *         HttpRequestWrapper overriding methods getLocale(), getLocales() to
 *         include the user's preferred locale.
 */
public class LocaleRequestWrapper extends HttpServletRequestWrapper {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(LocaleRequestWrapper.class);

	private final Locale preferredLocale;

	public LocaleRequestWrapper(HttpServletRequest decorated, Locale userLocale) {
		super(decorated);
		preferredLocale = userLocale;
		if (null == preferredLocale) {
			logger.error("preferred locale = null, it is an unexpected value!");
		}
	}

	/**
	 * @see javax.servlet.ServletRequestWrapper#getLocale()
	 */
	public Locale getLocale() {
		if (logger.isDebugEnabled()) {
			logger.debug("getLocale() - start"); //$NON-NLS-1$
		}

		if (null != preferredLocale) {
			if (logger.isDebugEnabled()) {
				logger.debug("getLocale() - end"); //$NON-NLS-1$
			}
			return preferredLocale;
		} else {
			Locale returnLocale = super.getLocale();
			if (logger.isDebugEnabled()) {
				logger.debug("getLocale() - end"); //$NON-NLS-1$
			}
			return returnLocale;
		}
	}

	/**
	 * @see javax.servlet.ServletRequestWrapper#getLocales()
	 */
	public Enumeration getLocales() {
		if (logger.isDebugEnabled()) {
			logger.debug("getLocales() - start"); //$NON-NLS-1$
		}

		if (null != preferredLocale) {
			List l = Collections.list(super.getLocales());
			if (l.contains(preferredLocale)) {
				l.remove(preferredLocale);
			}
			l.add(0, preferredLocale);
			Enumeration returnEnumeration = Collections.enumeration(l);
			if (logger.isDebugEnabled()) {
				logger.debug("getLocales() - end"); //$NON-NLS-1$
			}
			return returnEnumeration;
		} else {
			Enumeration returnEnumeration = super.getLocales();
			if (logger.isDebugEnabled()) {
				logger.debug("getLocales() - end"); //$NON-NLS-1$
			}
			return returnEnumeration;
		}
	}

}
